package com.studyyoun.android.nonghe.person.fragment;
/**
 * Created by zhaolong on 2017/10/16.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidlongs.pullrefreshrecyclerylib.common.PullRecyclerViewUtils;
import com.androidlongs.pullrefreshrecyclerylib.inter.PullRecyclerViewLinserner;
import com.androidlongs.pullrefreshrecyclerylib.inter.PullRecyclerViewOnItemClickLinserner;
import com.androidlongs.pullrefreshrecyclerylib.model.PullRecyclerMoreStatueModel;
import com.studyyoun.android.androidcommonbaselibrary.fragment.CommonBaseFragment;
import com.studyyoun.android.androidcommonbaselibrary.glide.CommonGlideUtils;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.exce.OkhttpException;
import com.studyyoun.android.androidcommonbaselibrary.utils.DateUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.home.activity.ArtDetaileActivity;
import com.studyyoun.android.nonghe.home.activity.VideoDetaileActivity;
import com.studyyoun.android.nonghe.home.model.ArtModel;
import com.studyyoun.android.nonghe.home.model.VideoModel;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.msg.activity.MsgDetaileActivity;
import com.studyyoun.android.nonghe.msg.model.MsgModel;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * class infation
 */
public class PersonCollectFragment extends CommonBaseFragment {
    private LinearLayout mMainContentLayout;
    private PullRecyclerViewUtils mPullRecyclerViewUtils;

    @Override
    protected int getCommonLayoutId() {
        return R.layout.fragment_collect_item_layout;
    }

    @Override
    protected void commonInitView(View view) {

        Bundle arguments = getArguments();
        if (arguments != null) {
            type = arguments.getString("pageType");
            if (TextUtils.equals(type, "文章")) {
                type = "art";
            } else if (TextUtils.equals(type, "视频")) {
                type = "video";
            } else if (TextUtils.equals(type, "晨起一刻")) {
                type = "mornig";
            }

        }


        mMainContentLayout = view.findViewById(R.id.ll_comment_item_content);


        //初始化
        mPullRecyclerViewUtils = PullRecyclerViewUtils.getInstance();

        //3初始化Recyclerview
        /**
         * 参数一 this Context实例
         * 参数二 单一布局模式条目布局ID
         * 参数三 数据集合
         * 参数四 回调监听
         */
        RelativeLayout relativeLayout = mPullRecyclerViewUtils.setRecyclerViewFunction(mContext, -1, mCommonArtModelList, mPullRecclerLinserner, mItemClickLinserner);

        //4相关设置

        //下拉刷新和上拉加载更多模式
        mPullRecyclerViewUtils.setRecyclerviewStatue(PullRecyclerViewUtils.RECYCLRYVIEW_STATUE.PULL_AND_UP);

        mPullRecyclerViewUtils.setFirstDefaultPageType(PullRecyclerViewUtils.SHOW_DEFAUTLE_PAGE_TYPE.LOADING);

        mPullRecyclerViewUtils.setPullScrollRecyclerLiserner(mOnPullRecyclerviewScrollLiserner);
        //5将recyclerview添加到当前显示的页面中
        mMainContentLayout.addView(relativeLayout);
    }

    @Override
    protected void commonFunction() {

    }

    @Override
    protected void commonDelayFunction() {

    }

    public void loadingDatas() {

        if (mCommonArtModelList.size() > 0) {
            LogUtils.d("加载缓存数据");
            return;
        } else {
            LogUtils.d("加载网络数据");
        }

        if (TextUtils.equals(type, "art")) {
            //加载数据
            loadingArtNetDataFunction();
        } else if (TextUtils.equals(type, "video")) {
            loadingVideoNetDataFunction();
        } else if (TextUtils.equals(type, "mornig")) {
            loadingMoringNetDataFunction();
        }

    }

    private void loadingMoringNetDataFunction() {
        String url = HttpUrlHelper.msgGetCollectListUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("pageIndex", "" + currentIndex);
        key.put("pageSize", "" + pageSize);
        key.put("collectType", "art");
        key.put("userId", "" + CommonUserHelper.getUserModel().getUserId());
        mPullRecyclerViewUtils.startLoadingAnimation();
        mPreLoadingTime = System.currentTimeMillis();

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(MsgModel.class) {
            @Override
            public void onSuccess(final Object obj) {


                long flagTime = System.currentTimeMillis();

                if (flagTime < 1500) {
                    flagTime = 1500 - flagTime;
                } else {
                    flagTime = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullRecyclerViewUtils.stopLoadingAnimation();
                        if (obj != null) {

                            List<MsgModel> artModels = (List<MsgModel>) obj;
                            if (artModels != null && artModels.size() > 0) {


                                for (MsgModel artModel : artModels) {

                                    PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();
                                    pullRecyclerMoreStatueModel.model = artModel;
                                    pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_my_collect_msg_mornig_text_layout;
                                    pullRecyclerMoreStatueModel.itemType = 3;

                                    mCommonArtModelList.add(pullRecyclerMoreStatueModel);

                                }
                                mPullRecyclerViewUtils.setLoadingDataList(mCommonArtModelList);

                            } else {
                                mPullRecyclerViewUtils.setLoadingDataList(null);
                            }


                        } else {
                            mPullRecyclerViewUtils.setLoadingDataList(null);
                        }
                    }
                }, flagTime);

            }

            @Override
            public void onFaile(Object obj) {
                mPullRecyclerViewUtils.stopLoadingAnimation();
                LogUtils.d("加载时刻失败");
                mPullRecyclerViewUtils.setLoadingDataList(null);
            }
        });
    }

    private int currentIndex = 0;
    private int pageSize = 30;
    private String type = "art";
    private long mPreLoadingTime = 0;

    private List<PullRecyclerMoreStatueModel> mCommonArtModelList = new ArrayList<>();

    private void loadingArtNetDataFunction() {

        String url = HttpUrlHelper.articleGetCollectListUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("pageIndex", "" + currentIndex);
        key.put("pageSize", "" + pageSize);
        key.put("collectType", "art");
        key.put("userId", "" + CommonUserHelper.getUserModel().getUserId());
        mPullRecyclerViewUtils.startLoadingAnimation();
        mPreLoadingTime = System.currentTimeMillis();

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(ArtModel.class) {
            @Override
            public void onSuccess(final Object obj) {


                long flagTime = System.currentTimeMillis();

                if (flagTime < 1500) {
                    flagTime = 1500 - flagTime;
                } else {
                    flagTime = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullRecyclerViewUtils.stopLoadingAnimation();
                        if (obj != null) {

                            List<ArtModel> artModels = (List<ArtModel>) obj;
                            if (artModels != null && artModels.size() > 0) {


                                for (ArtModel artModel : artModels) {

                                    PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();
                                    pullRecyclerMoreStatueModel.model = artModel;
                                    pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_home_art_layout;
                                    pullRecyclerMoreStatueModel.itemType = 1;

                                    mCommonArtModelList.add(pullRecyclerMoreStatueModel);

                                }
                                mPullRecyclerViewUtils.setLoadingDataList(mCommonArtModelList);

                            } else {
                                mPullRecyclerViewUtils.setLoadingDataList(null);
                            }


                        } else {
                            mPullRecyclerViewUtils.setLoadingDataList(null);
                        }
                    }
                }, flagTime);

            }

            @Override
            public void onFaile(Object obj) {
                mPullRecyclerViewUtils.stopLoadingAnimation();
                LogUtils.d("加载文章失败");
                mPullRecyclerViewUtils.setLoadingDataList(null);
            }
        });
    }

    private void loadingVideoNetDataFunction() {
        mPullRecyclerViewUtils.startLoadingAnimation();
        String url = HttpUrlHelper.articleGetCollectListUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("pageIndex", "" + currentIndex);
        key.put("pageSize", "" + pageSize);
        key.put("collectType", "" + type);
        key.put("userId", "" + CommonUserHelper.getUserModel().getUserId());

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(VideoModel.class) {
            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("加载视频成功");
                mPullRecyclerViewUtils.stopLoadingAnimation();
                if (obj != null) {
                    List<VideoModel> videoModels = (List<VideoModel>) obj;
                    LogUtils.d("加载文章成功");
                    if (videoModels != null && videoModels.size() > 0) {

//                        mArtModelList.addAll(artModels);
//
//                        ExecutorFunction.getInstance().addRunnableTask(new Runnable() {
//                            @Override
//                            public void run() {
//                                for (ArtModel artModel : artModels) {
//                                    mArtSqlDBHelper.insertArt(artModel);
//                                }
//                            }
//                        });

                        for (VideoModel videoModel : videoModels) {

                            PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = new PullRecyclerMoreStatueModel();
                            pullRecyclerMoreStatueModel.model = videoModel;
                            pullRecyclerMoreStatueModel.itemLayoutId = R.layout.item_home_video_layout;
                            pullRecyclerMoreStatueModel.itemType = 2;

                            mCommonArtModelList.add(pullRecyclerMoreStatueModel);

                        }
                        mPullRecyclerViewUtils.setLoadingDataList(mCommonArtModelList);

                    } else {
                        mPullRecyclerViewUtils.setLoadingDataList(null);
                    }
                } else {
                    mPullRecyclerViewUtils.setLoadingDataList(null);
                    LogUtils.e("obj is null");
                }
            }

            @Override
            public void onFaile(Object obj) {
                mPullRecyclerViewUtils.stopLoadingAnimation();
                OkhttpException retryException = (OkhttpException) obj;
                LogUtils.d("加载视频失败 " + retryException.exception);
                mPullRecyclerViewUtils.setLoadingDataList(null);
            }
        });
    }


    private PullRecyclerViewLinserner mPullRecclerLinserner = new PullRecyclerViewLinserner() {
        @Override
        public void loadMoreData() {
            mPullRecyclerViewUtils.setLoadingDataList(mCommonArtModelList);
        }

        @Override
        public void loadingRefresDataFunction() {
            mCommonArtModelList.clear();
            loadingDatas();
        }

        @Override
        public void setViewDatas(View itemView, int position, int itemType, Object object) {

            PullRecyclerMoreStatueModel pullRecyclerMoreStatueModel = (PullRecyclerMoreStatueModel) object;
            itemType = pullRecyclerMoreStatueModel.itemType;
            if (itemType == 1) {
                ArtModel artModel = (ArtModel) pullRecyclerMoreStatueModel.model;

                String artName = artModel.artName;
                TextView titleTextView = itemView.findViewById(R.id.tv_home_item_art_title);
                titleTextView.setText(artName);

                String imageUrl = artModel.artImageUrl;
                ImageView imageView = itemView.findViewById(R.id.iv_home_item_art_img);
                imageUrl = HttpUrlHelper.BaseImageHost + imageUrl;
                CommonGlideUtils.showImageView(mContext, R.mipmap.default_pic, imageUrl, imageView);


                String artFalg = artModel.artFalg;
                TextView falgTextView = itemView.findViewById(R.id.tv_home_item_art_flg);
                falgTextView.setText(artFalg);


                String author = artModel.author;
                TextView authorTextView = itemView.findViewById(R.id.tv_home_item_art_author);
                authorTextView.setText(author);


                String artReadCount = artModel.artReadCount;
                TextView artReadCountTextView = itemView.findViewById(R.id.tv_home_item_art_read);
                artReadCountTextView.setText(artReadCount + "阅读");


                List<String> articlPariseModels = artModel.articlPariseModels;
                String artParise = "0";
                if (articlPariseModels != null) {
                    artParise = String.valueOf(articlPariseModels.size());
                }
                TextView artPariseCountTextView = itemView.findViewById(R.id.tv_home_item_art_pra);
                artPariseCountTextView.setText(artParise);


                String artCreateTime = artModel.artCreateTime;
                TextView artCreateTimeTextView = itemView.findViewById(R.id.tv_home_item_art_date);
                artCreateTimeTextView.setText(DateUtils.getInstance().formatTime(Long.valueOf(artCreateTime), "yyyy-MM-dd"));


                TextView artIsTopTextView = itemView.findViewById(R.id.tv_home_item_art_is_top);
                TextView artIsRecommendTextView = itemView.findViewById(R.id.tv_home_item_art_is_recommend);

                artIsTopTextView.setVisibility(View.GONE);
                artIsRecommendTextView.setVisibility(View.GONE);


            } else if (itemType == 2) {
                VideoModel videoModel = (VideoModel) pullRecyclerMoreStatueModel.model;

                String artName = videoModel.getTitle().trim();
                TextView titleTextView = itemView.findViewById(R.id.tv_home_item_art_title);
                titleTextView.setText(artName);

                String imageUrl = videoModel.getImageUrl();
                ImageView imageView = itemView.findViewById(R.id.iv_home_item_art_img);
                imageUrl = HttpUrlHelper.BaseImageHost + imageUrl;
                CommonGlideUtils.showImageView(mContext, R.mipmap.default_pic, imageUrl, imageView);


                String artFalg = videoModel.getFalg();
                TextView falgTextView = itemView.findViewById(R.id.tv_home_item_art_flg);
                falgTextView.setText(artFalg);


                String author = "代码小狂人";
                TextView authorTextView = itemView.findViewById(R.id.tv_home_item_art_author);
                authorTextView.setText(author);


                String artReadCount = String.valueOf(videoModel.readCount);
                TextView artReadCountTextView = itemView.findViewById(R.id.tv_home_item_art_read);
                artReadCountTextView.setText(artReadCount + "");


                List<String> articlPariseModels = videoModel.getPariseUserIdList();
                String artParise = "0";
                if (articlPariseModels != null) {
                    artParise = String.valueOf(articlPariseModels.size());
                }
                TextView artPariseCountTextView = itemView.findViewById(R.id.tv_home_item_art_pra);
                artPariseCountTextView.setText(artParise);


                String artCreateTime = videoModel.getCreatTime();
                TextView artCreateTimeTextView = itemView.findViewById(R.id.tv_home_item_art_date);
                artCreateTimeTextView.setText(DateUtils.getInstance().formatTime(Long.valueOf(artCreateTime), "yyyy-MM-dd"));

                TextView artIsTopTextView = itemView.findViewById(R.id.tv_home_item_art_is_top);
                TextView artIsRecommendTextView = itemView.findViewById(R.id.tv_home_item_art_is_recommend);


                artIsTopTextView.setVisibility(View.GONE);
                artIsRecommendTextView.setVisibility(View.GONE);

            } else if (itemType == 3) {
                MsgModel msgModel = (MsgModel) pullRecyclerMoreStatueModel.model;

                TextView titleTextView = itemView.findViewById(R.id.tv_collect_msg_title);
                titleTextView.setText(msgModel.getMsgTitle());

                TextView contentTextView = itemView.findViewById(R.id.tv_collect_msg_content);
                contentTextView.setText(Html.fromHtml(msgModel.getMsgContent()));
                contentTextView.setClickable(true);
                contentTextView.setMovementMethod(LinkMovementMethod.getInstance());


            }
        }
    };
    private PullRecyclerViewOnItemClickLinserner mItemClickLinserner = new PullRecyclerViewOnItemClickLinserner() {
        @Override
        public void setonItemClick(int position, int itemType, Object object) {

            PullRecyclerMoreStatueModel moreStatueModel = (PullRecyclerMoreStatueModel) object;

            itemType = moreStatueModel.itemType;

            if (itemType == 1) {
                ArtModel videoModel = (ArtModel) moreStatueModel.model;
                Intent intent = new Intent(mContext, ArtDetaileActivity.class);
                intent.putExtra("artModelId", String.valueOf(videoModel.getId()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } else if (itemType == 2) {
                VideoModel videoModel = (VideoModel) moreStatueModel.model;

                Intent intent = new Intent(mContext, VideoDetaileActivity.class);
                intent.putExtra("videoId", String.valueOf(videoModel.getId()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            } else if (itemType == 3) {
                MsgModel msgModel = (MsgModel) moreStatueModel.model;
                LogUtils.d("msg click ");
                Intent intent = new Intent(mContext, MsgDetaileActivity.class);
                intent.putExtra("msgModel", msgModel);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        }
    };

    private PullRecyclerViewUtils.OnPullRecyclerviewScrollLiserner mOnPullRecyclerviewScrollLiserner = new PullRecyclerViewUtils.OnPullRecyclerviewScrollLiserner() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy, LinearLayoutManager mLinearLayoutManager) {

        }
    };
}
